/**
 * 
 */
package it.eng.get.pdfwe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.w3c.tidy.Configuration;
import org.w3c.tidy.Tidy;

import com.lowagie.text.Element;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

/**
 * @author <div style="width: 100%; height: 2em;
 * background-repeat: repeat-x; 
 * background-image: url(http://www.mysoftworks.net/images/author_back.gif);" >
 * <a style="float: right; font-size: .9em; margin: 1.2em .5em .1em .1em; color: #658A16; color: 658A16; font-family: helvetica; font-weight: bold; text-decoration: none" href="http://www.mysoftworks.net">
 * Antonio Giovannetti </a>
 * </div>
 */
public class PDFWeUtils {
	
	private static Tidy defaultTidy = null;

	static {
		defaultTidy = new Tidy();
		defaultTidy.setXHTML(true);
		defaultTidy.setQuoteAmpersand(false);
		defaultTidy.setDocType("omit");
	}
	
	public static void tidyParse(Tidy tidy,ByteArrayInputStream is,ByteArrayOutputStream os) {
		if (is==null) return;
		if (os==null) return;
		os.reset();
		if (tidy==null) {
			tidy=defaultTidy;
			tidy.setCharEncoding(Configuration.UTF8);
			tidy.setNumEntities(true);
			tidy.setBreakBeforeBR(true);
			tidy.setXHTML(true);
			tidy.setQuoteAmpersand(false);
			tidy.setDocType("omit");
			tidy.setQuoteNbsp(true);

		}
		tidy.parse(is,os);		
	}
	
	
	public static byte[] getPDFError(String message) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			com.lowagie.text.Document document = new com.lowagie.text.Document();
			PdfWriter.getInstance(document, baos);
			document.open();
			Paragraph p = new Paragraph(message, FontFactory.getFont(FontFactory.HELVETICA, 10));
			p.setAlignment(Element.ALIGN_LEFT);
			document.add(p);
			document.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static byte[] getPDFError(Exception e) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			com.lowagie.text.Document document = new com.lowagie.text.Document();
			PdfWriter.getInstance(document, baos);
			document.open();
			StringWriter sw = new StringWriter();
			StringBuffer buff = sw.getBuffer();
			buff.append("Errore: \n");
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			Paragraph p = new Paragraph(buff.toString(), FontFactory.getFont(FontFactory.HELVETICA, 10));
			p.setAlignment(Element.ALIGN_LEFT);
			document.add(p);
			document.close();
			return baos.toByteArray();
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	
}
